package com.zoctan.api.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoctan.api.common.jwt.JwtUtil;
import com.zoctan.api.common.response.Result;
import com.zoctan.api.common.response.ResultGenerator;
import com.zoctan.api.common.util.AssertUtils;
import com.zoctan.api.dto.AccountDto;
import com.zoctan.api.dto.AccountWithRole;
import com.zoctan.api.entity.Account;
import com.zoctan.api.service.AccountService;
import com.zoctan.api.service.impl.AccountDetailsServiceImpl;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * @author Zoctan
 * @date 2018/06/09
 */
@RestController
@RequestMapping("/account")
@Validated
public class AccountController {
  @Resource private AccountService accountService;
  @Resource private AccountDetailsServiceImpl userDetailsService;
  @Resource private JwtUtil jwtUtil;

  @PostMapping
  public String register(
      @RequestBody @Valid final AccountDto account, final BindingResult bindingResult) {
    // {"name":"123456", "password":"123456", "email": "123456@qq.com"}
    AssertUtils.state(bindingResult.hasErrors(), bindingResult.getFieldError().getDefaultMessage());
    this.accountService.save(account);
    return this.getToken(account.getName());
  }

  @PreAuthorize("hasAuthority('account:delete')")
  @DeleteMapping("/{id}")
  public void delete(@PathVariable final Long id, final Principal principal) {
    final Account dbAccount = this.accountService.getById(id);
    AssertUtils.notNull(dbAccount, "用户不存在");
    this.accountService.deleteById(id);
  }

  @PostMapping("/password")
  public Boolean validatePassword(@RequestBody final Account account) {
    final Account dbAccount = this.accountService.getById(account.getId());
    return this.accountService.verifyPassword(account.getPassword(), dbAccount.getPassword());
  }

  /** 更新其他账户的资料 */
  @PreAuthorize("hasAuthority('account:update')")
  @PutMapping("/{id}")
  public void updateOthers(
      @PathVariable final Long id, @RequestBody final Account account, final Principal principal) {
    final Account dbAccount = this.accountService.getById(id);
    AssertUtils.notNull(dbAccount, "用户不存在");
    this.accountService.update(account);
  }

  /** 更新自己的资料 */
  @PutMapping("/detail")
  public String updateMe(@RequestBody final Account account) {
    this.accountService.update(account);
    final Account dbAccount = this.accountService.getById(account.getId());
    return this.getToken(dbAccount.getName());
  }

  /** 其他账户的资料 */
  @PreAuthorize("hasAuthority('account:detail')")
  @GetMapping("/{id}")
  public Account detail(@PathVariable final Long id) {
    return this.accountService.getById(id);
  }

  /** 自己的资料 */
  @GetMapping("/detail")
  public Account detail(final Principal principal) {
    return this.accountService.findDetailByName(principal.getName());
  }

  @PreAuthorize("hasAuthority('account:list')")
  @GetMapping
  public PageInfo<AccountWithRole> list(
      @RequestParam(defaultValue = "0") final Integer page,
      @RequestParam(defaultValue = "0") final Integer size) {
    PageHelper.startPage(page, size);
    final List<AccountWithRole> list = this.accountService.listAllWithRole();
    return new PageInfo<>(list);
  }

  @PreAuthorize("hasAuthority('account:search')")
  @PostMapping("/search")
  public PageInfo<AccountWithRole> search(@RequestBody final Map<String, Object> param) {
    PageHelper.startPage((Integer) param.get("page"), (Integer) param.get("size"));
    final List<AccountWithRole> list = this.accountService.findWithRoleBy(param);
    return new PageInfo<>(list);
  }

  @PostMapping("/token")
  public Result<String> login(@RequestBody final Account account) {
    // {"name":"admin", "password":"admin123"}
    // {"email":"admin@qq.com", "password":"admin123"}
	boolean bo = account.getName() == null && account.getEmail() == null;
	AssertUtils.state(!bo, "用户名或邮箱为空");
	AssertUtils.hasText(account.getPassword(), "密码为空");
	
	Account dbAccount = null;
	if (account.getName() != null) {
		// 用户名登录
	    dbAccount = this.accountService.getByName(account.getName());
	    AssertUtils.notNull(dbAccount, "用户名错误");
	} else if (account.getEmail() != null) {
		// 邮箱登录
		dbAccount = this.accountService.getByEmail(account.getEmail());
	    AssertUtils.notNull(dbAccount, "邮箱错误");
	}
	// 用户名与邮箱都为空
	AssertUtils.notNull(dbAccount, "用户名和邮箱为空");

    AssertUtils.state(this.accountService.verifyPassword(account.getPassword(), dbAccount.getPassword()), "密码错误");
    // 更新登录时间
    this.accountService.updateLoginTimeByName(dbAccount.getName());
    return ResultGenerator.genOkResult(this.getToken(dbAccount.getName()));
  }

  @DeleteMapping("/token")
  public void logout(final Principal principal) {
    return;
  }

  /** 获得 token */
  private String getToken(final String name) {
    final UserDetails accountDetails = this.userDetailsService.loadUserByUsername(name);
    final String token = this.jwtUtil.sign(name, accountDetails.getAuthorities(), true);
    return token;
  }
}
